#include "../include/head.h"
int user_count = 0;

// 用户管理
void load_users() {
    FILE *fp = fopen("./student_management/data/user.txt", "rb");
    if (!fp) return;
    
    fread(&user_count, sizeof(int), 1, fp);
    fread(users, sizeof(User), user_count, fp);
    
    fclose(fp);
}

void save_users() {
    FILE *fp = fopen("./student_management/data/user.txt", "wb");
    if (!fp) {
        perror("保存用户失败");
        return;
    }
    
    fwrite(&user_count, sizeof(int), 1, fp);
    fwrite(users, sizeof(User), user_count, fp);
    
    fclose(fp);
}

bool login(User *current_user) {
    char username[20], password[20];
    printf("用户名: ");
    scanf("%19s", username);
    printf("密码: ");
    scanf("%19s", password);
    
    for (int i = 0; i < user_count; i++) {
        if (strcmp(username, users[i].username) == 0 && 
            strcmp(password, users[i].password) == 0) {
            *current_user = users[i];
            printf("%s登录成功!\n", current_user->is_teacher ? "教师" : "学生");
            return true;
        }
    }
    
    printf("用户名或密码错误!\n");
    return false;
}

void register_user(bool is_teacher) {
    if (user_count >= MAX_USERS) {
        printf("用户数量已达上限!\n");
        return;
    }
    
    User new_user;
    printf("用户名: ");
    scanf("%19s", new_user.username);
    printf("密码: ");
    scanf("%19s", new_user.password);
    new_user.is_teacher = is_teacher;
    
    // 检查用户名是否已存在
    for (int i = 0; i < user_count; i++) {
        if (strcmp(new_user.username, users[i].username) == 0) {
            printf("用户名已存在!\n");
            return;
        }
    }
    
    users[user_count++] = new_user;
    save_users();
    printf("%s注册成功!\n", is_teacher ? "教师" : "学生");
}
